package com.ternnetwork;

import javax.servlet.http.HttpServletResponse;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

@SpringBootApplication
//启用客户端发现
@EnableDiscoveryClient
//启用auth2资源服务器
@EnableResourceServer
//启用方法拦截
@EnableGlobalMethodSecurity(prePostEnabled = true)

//开启缓存功能
@EnableCaching
public class WorkflowServiceProducerApp  extends ResourceServerConfigurerAdapter{

		public static void main(String[] args) {
			SpringApplication.run(WorkflowServiceProducerApp.class, args);
		}
		
		
	    //让转换null时不报错
		@Bean
		public ObjectMapper objectMapper() {
		     return new ObjectMapper().disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
		}
	
	
		 @Override
		    public void configure(HttpSecurity http) throws Exception {
		        http
		                .csrf().disable()
		                .exceptionHandling()
		                .authenticationEntryPoint((request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED))
		                .and()
		                .requestMatchers()
		                .antMatchers("/**")
		                .and()
		                .authorizeRequests()
		                .antMatchers("/**")
		                .authenticated()
		                .and()
		                .httpBasic();
		    }
	
		@Override
		public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
			resources
			.resourceId("WRIGTH")
			.tokenStore(jwtTokenStore());
		}
	
		@Bean
		protected JwtAccessTokenConverter jwtTokenConverter() {
			JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
			converter.setSigningKey("QWERFDSAZXCV");
			return converter;
		}
	
		@Bean
		public TokenStore jwtTokenStore() {
			return new JwtTokenStore(jwtTokenConverter());
		}
}
